const fs = require('fs')

const file = fs.readFileSync('./target.txt', {
  encoding: 'utf-8'
})

class WordCount extends Map {
  constructor(defaultValue) {
    super()
    this.defaultValue = defaultValue
  }

  get(key) {
    if (this.has(key)) {
      return super.get(key)
    } else {
      return this.defaultValue
    }
  }
}

class Histogram {
  constructor() {
    this.letterCount = new WordCount(0)
    this.totalCount = 0
  }

  add(word) {
    /* 过滤非法字符 */
    if (/[^A-Z]/.test(word)) return
    let wordNum = this.letterCount.get(word)
    if (this.letterCount.has(word)) {
      this.letterCount.set(word, wordNum + 1)
    } else {
      this.letterCount.set(word, 1)
    }
    this.totalCount++
  }

  toString() {
    let entries = Array.from(this.letterCount.entries())
    entries.sort((a, b) => b[1] - a[1])


    /* 过滤掉低于1%的字母 */
    entries = entries.filter(v => v[1] / this.totalCount > 0.01)
    const line = entries.map(v => {
      let percent = v[1] / this.totalCount * 100
      let prefix = ''.padStart(Math.floor(percent), '#')
      return `${v[0]} ${prefix} ${percent.toFixed(2)}%`
    })
    return line.join('\n')
  }
}

let histogram = new Histogram()
const FILE = file.toUpperCase()
for (const s of FILE) {
  histogram.add(s)
}

console.log(histogram.toString())
